<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { ApiSysFilesInput, SysfilesApi, type ApiSysLogInput, type ApiSysLogOut } from '@/api-services';
import { UserApi } from '@/api-services/apis/user-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { REG_PWD, REG_USER_NAME } from '@/constants/reg';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { NetoKit } from '@/typings/neto';
import { SyslogApi } from '@/api-services/apis/syslog-api';
import { GetThumbnailUrl } from '@/components/file/image/file-helper';

// import Upload from '@/components/file-upload/index.vue';

defineOptions({
  name: 'FileLocalOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  editingId?: number | string | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
  (e: 'upload-success', id: number): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t('page.fileManage.addFile'),
    edit: $t('page.fileManage.editFile')
  };
  return titles[props.operateType];
});


// const regs: Record<UI.TableOperateType, App.Global.FormRule> = {
//   edit: { required: false },
//   add: {
//     required: true,
//     pattern: REG_PWD,
//     message: $t('form.pwd.invalid'),
//     trigger: 'change'
//   }
// };

// type Model = NonNullable<Pick<
//   ApiSysLogOut,
//   'account' | 'nick' | 'phone' | 'email' | 'isEnable'
// >>;
type Model = NetoKit.IsNonNullable<{
  [K in keyof Pick<ApiSysFilesInput, 'id' | 'category' | 'catetoryType' | 'fId' | 'tags' | 'fileStoLocType' | 'name' | 'isOpen' |
    'sort' | 'extension' | 'relFileFloder' | 'filePath' | 'imgfilepathThumbnail' | 'isWwwroot' | 'sourceDataId' | 'sourceDataType' | 'field'>]: NonNullable<
      ApiSysFilesInput[K]
    >;
}>;
const model = ref(createDefaultModel());
// string转换为number
// model.value.roleIds = model.value.roleIdStr?.split(',').map(Number);
function createDefaultModel(): Model {
  return {
    id: 0,
    name: '',
    sort: 0,
    category: '',
    catetoryType: 0,
    fId: '',
    tags: '',
    fileStoLocType: 0,
    isOpen: false,
    extension: '',
    relFileFloder: '',
    filePath: '',
    imgfilepathThumbnail: '',
    isWwwroot: false,
    sourceDataId: '',
    sourceDataType: '',
    field: ''
  };
}

// type RuleKey = 'account' | 'nick' /*| 'pwd' */;

// const formRules = {
//   account: [
//     {
//       pattern: REG_USER_NAME,
//       message: $t('form.userName.invalid'),
//       trigger: 'change'
//     },
//     defaultRequiredRule
//   ],
//   nick: [defaultRequiredRule],
//   addPwd: [
//     {
//       required: true,
//       pattern: REG_PWD,
//       message: $t('form.pwd.invalid'),
//       trigger: 'change'
//     }
//   ]
// } satisfies Record<string, App.Global.FormRule[]>;


async function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.editingId) {
    //查询id对应的数据
    const [err, res] = await feature(getAPI(SysfilesApi).get(Number(props.editingId)));
    queryDone(err, async () => {
      if (res?.data.data) {
        Object.assign(model.value, res.data.data);

      }
    })
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  // model.value.roleIds = model.value.roleIds.map(it => it.toString());
  // 提交请求
  const [err, res] = await feature(getAPI(SysfilesApi).update(model.value));

  queryDone(err, async () => {
    if (res?.data.data) {
      window.$message?.success($t('common.updateSuccess'));
      closeModal();
      emit('submitted');
    }
  });
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});

const thumbnailUrl = computed(() => {
  return GetThumbnailUrl(model.value.fId)
});


/**
 * 上传结束
 */
const beforeUpload = (id: number) => {
  //更新弹窗性质
  if (id) {
    console.log(id);
    emit('upload-success', id)
  }
}

//对外开放重新加载字段的方法
const reloadFields = () => {
  //重新加载数据
  console.log('reloadFields');
  // restoreValidation();
  handleInitModel();
}

defineExpose({
  reloadFields
});
</script>

<template>
  <NModal v-model:open="visible" :title="title" :show-full-screen="true" width="1000px">
    <!-- :rules="formRules" -->
    <ElForm ref="formRef" label-width="auto" :model="model">
      <ElRow :gutter="16" wrap>

        <ElCol :lg="24" :xs="24" v-if="operateType === 'add'">
          <ElFormItem :label="$t('page.fileManage.uploadFile')" name="upload">
            <NFileUpload :show-upload-list="false" upload-type="button" ref="uploadRef" @submitted="beforeUpload"
              category="local-list" :allowExtensions="['.jpg', '.png']" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.name')" name="name">
            <ElInput v-model="model.name" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem v-if="model.extension === '.jpg' || model.extension === '.png'"
            :label="$t('page.fileManage.localFile.thumbnail')">
            <!-- 如果是图片,则展示图片 -->
            <NImage :url="thumbnailUrl" :maxHeight="100" :maxWidth="100" />
          </ElFormItem>
          <!-- 如果不是图片,则提供下载 -->
          <ElFormItem v-else :label="$t('page.fileManage.localFile.download')" name="fId">
            <NDownload :fId="model.fId" />
          </ElFormItem>
        </ElCol>

        <!-- 关联字段 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem label="fId" name="fId">
            <ElInput v-model="model.fId" />
          </ElFormItem>
        </ElCol>

        <!-- 文件类型（带选项）-->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.categoryType')" name="categoryType">
            <ElSelect v-model="model.catetoryType">
              <ElOption :value="0" :label="$t('page.fileManage.localFile.categoryTypeEnum.default')" />
              <ElOption :value="1" label="logo" />
            </ElSelect>
          </ElFormItem>
        </ElCol>


        <!-- 布尔类型 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.isOpen')" name="isOpen">
            <ElSwitch v-model:model-value="model.isOpen" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.isWwwroot')" name="isWwwroot">
            <ElSwitch v-model:model-value="model.isWwwroot" disabled />
          </ElFormItem>
        </ElCol>



        <!-- 普通文本字段 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.category')" name="category">
            <ElInput v-model="model.category" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.extension')" name="extension">
            <ElInput v-model="model.extension" />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.tags')" name="tags">
            <ElInput v-model="model.tags" />
          </ElFormItem>
        </ElCol>




        <!-- 源数据ID -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.sourceDataId')" name="sourceDataId">
            <ElInput v-model="model.sourceDataId" />
          </ElFormItem>
        </ElCol>


        <!-- 源数据类别 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.sourceDataType')" name="sourceDataType">
            <ElInput v-model="model.sourceDataType" />
          </ElFormItem>
        </ElCol>
        <!-- 其他字段 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.field')" name="field">
            <ElInput v-model="model.field" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 文件夹路径 -->
          <ElFormItem :label="$t('page.fileManage.localFile.relFileFoloder')" name="relFileFloder">
            <ElInput v-model="model.relFileFloder" disabled />
          </ElFormItem>
        </ElCol>
        <!-- 存储相关 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.fileStoLocType')" name="fileStoLocType">
            <ElSelect v-model="model.fileStoLocType" disabled>
              <!-- 本地存储 -->
              <ElOption :value="0" :label="$t('page.fileManage.localFile.fileStoLocTypeEnum.local')" />
              <!-- 阿里云 -->
              <ElOption :value="1" :label="$t('page.fileManage.localFile.fileStoLocTypeEnum.aliCloud')" />
              <!-- 腾讯云 -->
              <ElOption :value="2" :label="$t('page.fileManage.localFile.fileStoLocTypeEnum.tencentCloud')" />
              <!-- 华为云 -->
              <ElOption :value="3" :label="$t('page.fileManage.localFile.fileStoLocTypeEnum.huaweiCloud')" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 长文本字段 -->
        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.filePath')" name="filePath">
            <ElInput type="textarea" v-model="model.filePath" :auto-size="{ minRows: 2, maxRows: 5 }" disabled />
          </ElFormItem>
        </ElCol>


        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.imgfilepathThumbnail')" name="imgfilepathThumbnail">
            <ElInput type="textarea" v-model="model.imgfilepathThumbnail" :auto-size="{ minRows: 2, maxRows: 5 }"
              disabled />
          </ElFormItem>
        </ElCol>
        <!-- 数字类型（自由输入）-->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.fileManage.localFile.sort')" name="sort">
            <ElInputNumber v-model="model.sort" style="width: 100%" :min="0" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
